import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from '../actions/index';
import ListEmpty from 'atComponents/ListEmpty';
import BranchAndTagSelect from 'components/branchAndTagSelect';
import CommitInfoMedia from 'components/commitInfoMedia';
import Pagination from 'components/pagination';
import {
  Header,
  Body,
  BodyContent,
  Content,
  OperationBar,
  YunxiaoList,
  SearchIcon,
} from '@alife/devops-ui';
import ProjectBreadcrumb from 'components/pathBreadcrumb/commitBreadcrumb.jsx';
import { navigate } from 'utils/router';
import { enterPage, Perf } from 'utils/track';
import utils from 'utils';
import debounce from 'lodash.debounce';
import KEYCODE from 'utils/keycode';
import { ENUM } from 'utils/constants';
import CommitsSkeleton from 'components/skeleton/commits';
import intl from '../../../../../../../locale';

const { ctrlKey } = ENUM.getOSKeyMap();
const extractDate = (commitItem) => {
  const dateStr = commitItem.created_at;
  return dateStr.substr(0, dateStr.indexOf('T'));
};
const { resourceSubject, pathResource } = window.FORCE;
class Root extends Component {
  constructor(props) {
    super(props);
    this.changeInput = debounce(() => {
      this.props.getCommits(1);
      this.props.updateCommitsPage(1);
    }, 500);
  }

  componentDidMount() {
    this.props.getCommits(this.props.commitsPage || 1);
    const isTooLarge = utils.isTooLarge(this.props.pageInfo.pathResource);
    if (isTooLarge && document.getElementById('container')) {
      document.getElementById('container').classList.add('has-too-large-tip');
    }
    enterPage('Repo-Commits', {
      sendPerf: false,
    });

    document.addEventListener('keydown', this.handleKeyCodeEvent);
  }

  handleKeyCodeEvent = (e) => {
    // ctrl + / 进行搜索
    if (e[ctrlKey] && e.keyCode === KEYCODE.SPLIT) {
      document.querySelector('.search-ctrl>button').click();
      document.querySelector('.search-ctrl input').focus();
    }
  };

  componentDidUpdate(prevProps) {
    if (prevProps.repoSize !== this.props.repoSize) {
      const isTooLarge = utils.isTooLarge(this.props.pageInfo.pathResource);
      if (isTooLarge && document.getElementById('container')) {
        document.getElementById('container').classList.add('has-too-large-tip');
      }
    }
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.handleKeyCodeEvent);
    if (document.getElementById('container')) {
      document.getElementById('container').classList.remove('has-too-large-tip');
    }
  }

  handleInputChange = (value) => {
    this.props.updateData({
      filterText: value,
    });

    this.changeInput();
  };

  getGroupList = (commits) => {
    const resourcePath = resourceSubject.path || '';
    if (!(commits && commits.length)) {
      return [];
    }
    const groupedCommits = commits.reduce((r, c) => {
      const date = extractDate(c);
      if (date in r) {
        r[date].push(c);
      } else {
        r[date] = [c];
      }
      return r;
    }, {});

    const dateList = [];
    commits.forEach((item) => {
      const date = extractDate(item);
      if (!dateList.includes(date)) {
        dateList.push(date);
      }
    });

    const { projectInfo } = this.props;

    const mediaList = dateList.map((date, dateIndex) => {
      const dateCommits = groupedCommits[date];
      return (
        <div className="project-content-list no-padding" key={date}>
          <div className="project-content-list-header secondary" key={date}>
            <span>{date}</span>
          </div>
          <div>
            <YunxiaoList
              dataSource={dateCommits}
              renderItem={(commitItem, commitIndex) => (
                <CommitInfoMedia
                  commitInfo={{ ...commitItem }}
                  projectInfo={projectInfo}
                  useForList
                  isSrcBtnShow
                  showCommentNum
                  resourcePath={resourcePath}
                  isNeedRestart={dateIndex === 0 && commitIndex === 0}
                />
              )}
            />
          </div>
        </div>
      );
    });

    return mediaList;
  };

  onChange = (value) => {
    // 切换分支，刷新页面
    navigate(
      `/${pathResource.fullPath}/${resourceSubject.subject}/${utils.revisionEncodeURI(value)}/${
        resourceSubject.path
      }`,
      { state: { forceUpdate: true } },
    );
  };

  renderEmpty = () => {
    const { filterText } = this.props;
    return (
      <ListEmpty
        type="project"
        content=""
        description={
          filterText
            ? intl.get({
                id: 'code-assets.projectCommits.containers.root.NoSearchResults',
                defaultMessage: '搜索无结果',
              })
            : intl.get({
                id: 'code-assets.projectCommits.containers.root.NoSubmissionRecords',
                defaultMessage: '暂无提交记录',
              })
        }
        imgType={filterText ? 'search' : 'none'}
        fullPage
      />
    );
  };

  onChangePage = (page, cb) => {
    this.props.getCommits(page, undefined, cb);
    this.props.updateCommitsPage(page);
  };

  render() {
    const resourcePath = resourceSubject.path || '';
    const {
      isLoading,
      commits,
      currentPage,
      total,
      filterText,
      // projectInfo,
    } = this.props;

    const dataSource = this.getGroupList(commits);

    return (
      <>
        <Header
          title={
            <>
              {intl.get({
                id: 'code-assets.projectCommits.containers.root.Submitted',
                defaultMessage: '提交',
              })}
              <BranchAndTagSelect
                {...this.props}
                hasBorder
                onChange={this.onChange}
                style={{ marginLeft: 20, width: 154 }}
              />
            </>
          }
          operation={
            <SearchIcon
              direction="rtl"
              placeholder={intl.get({
                id: 'code-assets.projectCommits.containers.root.SearchForSubmittedContent',
                defaultMessage: '搜索提交内容',
              })}
              onChange={this.handleInputChange}
              className="search-ctrl"
              value={filterText}
            />
          }
          marginLarge
        />

        <Body>
          <BodyContent>
            {resourcePath ? (
              <OperationBar className="commit-list-header">
                <span className="bread-wrapper">
                  <ProjectBreadcrumb {...this.props} />
                </span>
              </OperationBar>
            ) : null}
            <Content className="commit-list-body">
              {!isLoading ? (
                <>
                  {dataSource.length === 0 ? this.renderEmpty() : <div>{dataSource}</div>}

                  <Perf page={'Repo-Commits'} />
                </>
              ) : (
                <CommitsSkeleton />
              )}
            </Content>
            <Pagination
              onChange={this.onChangePage}
              type="simple"
              total={total}
              current={currentPage}
            />
          </BodyContent>
        </Body>
      </>
    );
  }
}

export default connect(
  (state) => ({
    ...state.project.projectCommits,
    projectInfo: state.project.root.projectInfo,
    pageInfo: state.root.pageInfo,
    genWatermarkimage: state.project.root.genWatermarkimage,
    commitsPage: state.project.root.commitsPage,
  }),
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
